import { compressImg } from '@/compress'
export default {
    /**
	 * h5多媒体文件获取
	 * @param accept 多媒体类型
	 * @param capture 启用摄像头或者麦克风，camera - 摄像头，microphone - 麦克风
	 * @param callback 回调
	 */
	inputFile(accept, capture, callback, baseSize = 50 * 1024, needRotate = true) {

		window.mediaConig = {
			accept,
			capture
		}

		let fileInputHtml = '';
		if (capture) {
			fileInputHtml =
				`<input id="mediaInput" onchange="mediaInputChange()" type="file" accept="${accept}/*,${capture}" capture="${capture}" style="border: none;color: #FFF;height: 0px;width:0px;left: -1000em;text-indent:-1000em;">`;
		} else {
			fileInputHtml =
				`<input id="mediaInput" onchange="mediaInputChange()" type="file" accept="${accept}/*" style="border: none;color: #FFF;height: 0px;width:0px;left: -1000em;text-indent:-1000em;">`;
		}

		window.mediaInputChange = function () {
			let file = document.getElementById('mediaInput').files[0]
			const type = file.type;

			if (window.mediaConig.capture) {
				// 实时拍摄需要校验文件来源和文件类型
				if (accept == 'image') {
					if (type.indexOf('image') == -1) {
						return alert('上传文件格式不正确')
					}
				}

				if (accept == 'video') {
					if (type.indexOf('video') == -1) {
						return alert('上传文件格式不正确')
					}
				}
			}

			// 只支持图片压缩
			if (accept == 'image') {
				compressImg(file, baseSize, needRotate).then(function (data) {
					typeof callback === 'function' && callback(data)
				}).catch(function (err) {
					typeof callback === 'function' && callback(file)
				})

			} else {
				typeof callback === 'function' && callback(file)
			}
		}

		let inputBox = null;
		if (document && document.getElementById) {

			if (document.getElementById('inputBox')) {
				document.body.removeChild(document.getElementById("inputBox"))
			}

			if (document.getElementById('H5_MEDIA_IMG')) {
				document.body.removeChild(document.getElementById("H5_MEDIA_IMG"))
			}

			if (accept == 'image') {
				let h5img = document.createElement('img');
				h5img.id = 'H5_MEDIA_IMG';
				h5img.src = '';

				document.body.appendChild(h5img)
			}

			inputBox = document.createElement('div')
			inputBox.id = 'inputBox'
			inputBox.innerHTML = fileInputHtml
			document.body.appendChild(inputBox)
			document.getElementById('mediaInput').click()
		}

	}
}